package drds.server.server.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import drds.server.route.parser.core.ShardInfoVisitor;
import drds.server.sqlparser.parser.StatementParser;
import drds.server.sqlparser.sqlobject.statement.Statement;

public class SchemaUtil {
	public static SchemaInfo parseSchema(String sql) {
		StatementParser parser = new StatementParser(sql);
		return parseTables(parser.parseStatement(), new ShardInfoVisitor());
	}

	public static String parseShowTableSchema(String sql) {
		Matcher ma = pattern.matcher(sql);
		if (ma.matches() && ma.groupCount() >= 5) {
			return ma.group(5);
		}
		return null;
	}

	private static SchemaInfo parseTables(Statement statement, ShardInfoVisitor schemaStatVisitor) {

		statement.accept(schemaStatVisitor);
		String key = schemaStatVisitor.getCurrentOnlyTableName();

		if (key != null) {
			SchemaInfo schemaInfo = new SchemaInfo();
			schemaInfo.table = key;
			return schemaInfo;
		}

		return null;
	}

	public static class SchemaInfo {
		public String table;
	}

	private static Pattern pattern = Pattern.compile("^\\s*(SHOW)\\s+(FULL)*\\s*(TABLES)\\s+(FROM)\\s+([a-zA-Z_0-9]+)\\s*([a-zA-Z_0-9\\s]*)", Pattern.CASE_INSENSITIVE);

	public static void main(String[] args) {
		String pat3 = "show  full  tables from  base like ";
		Matcher ma = pattern.matcher(pat3);
		if (ma.matches()) {
			System.out.println(ma.groupCount());
			System.out.println(ma.group(5));
		}

	}
}
